package com.blb.edugatewayservice.filter;

import com.blb.common.entity.ResponseStatus;
import com.blb.common.entity.Student;
import com.blb.common.util.JwtUtils;
import com.blb.common.util.RsaUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * 微服务全局登录验证过滤器
 */
@Slf4j
@Component
public class ServiceAuthenticationFilter implements GlobalFilter, Ordered {

    //白名单
    @Resource
    private WhiteListConfigProperties whiteListConfigProperties;
//    private String[] whiteList = {"/login","/logout","/search/courses"};

    /**
     * 对所有请求进行过滤
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getURI().getPath();
        //对白名单url进行放行
        for(String list : whiteListConfigProperties.getWhiteList()){
            if(url.contains(list)){
                log.info("白名单放行：{}",url);
                return chain.filter(exchange);
            }
        }
        //获得请求头中的token
        String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if(StringUtils.isEmpty(token)){
            log.error("用户token为空");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //给客户端返回错误提示信息
            DataBuffer wrap = response.bufferFactory().wrap(ResponseStatus.AUTH_ERROR.getMessage().getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        //对token进行验证
        try {
            Student student = JwtUtils.getUserFromToken(token, RsaUtils.publicKey);
            //成功放行
            log.info("用户验证成功：{}",student);
            return chain.filter(exchange);
        } catch (Exception e) {
            log.error("用户验证失败",e);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //给客户端返回错误提示信息
            DataBuffer wrap = response.bufferFactory().wrap(ResponseStatus.AUTH_ERROR.getMessage().getBytes());
            return response.writeWith(Mono.just(wrap));
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
